package com.marver.common.aspect;

import com.marver.common.Global;
import com.marver.common.annotation.DataFilter;
import com.marver.common.exception.HmException;
import com.marver.common.utils.StringUtils;
import com.marver.entity.qo.Param;
import com.marver.entity.sys.User;
import com.marver.shiro.ShiroUtils;
import com.marver.sys.service.DeptService;
import com.marver.sys.service.RoleDeptService;
import com.marver.sys.service.UserRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description: 数据过滤切面类
 * @Author: Marver
 * @date: 2018-04-25 18:06
 **/
@Aspect
@Component
public class DataFilterAspect {
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleDeptService roleDeptService;
    @Autowired
    private DeptService deptService;

    @Pointcut("@annotation(com.marver.common.annotation.DataFilter)")
    public void dataFilterCut(){

    }

    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) throws Throwable{
        Object params = point.getArgs()[0];
        if(params!=null && params instanceof Param){
            User user = ShiroUtils.getUser();
            //普通用户进行过滤
            if (user.getId() != Global.SUPER_ADMIN){
                Param param = (Param) params;
                param.setSqlFilter(getSQLFilter(user, point));
            }
            return;
        }
        throw new HmException("数据权限接口，Param类参数有误，且不能为NULL");
    }

    /**
     * 获取过滤的sql
     * @param user
     * @param point
     * @return
     */
    private String getSQLFilter(User user, JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);
        //获取表别名
        String tableAilas = dataFilter.tableAlias();
        if(StringUtils.isNotBlank(tableAilas)){
            tableAilas +=".";
        }
        //部门ID列表
        Set<Long> deptIdList = new HashSet<>();
        //用户角色对应部门ID列表
        List<Long> roleIdList = userRoleService.queryUserRoleIdList(user.getId());
        if(roleIdList.size()>0){
            List<Long> userRoleDeptIdList = roleDeptService.queryDeptIdList(roleIdList.toArray(new Long[roleIdList.size()]));
            deptIdList.addAll(userRoleDeptIdList);
        }
        //用户子部门ID列表
        if(dataFilter.subDept()){
            List<Long> subDeptIdList = deptService.getSubDeptIdList(user.getDeptId());
            deptIdList.addAll(subDeptIdList);
        }

        StringBuilder sqlFilter = new StringBuilder();
        sqlFilter.append(" (");

        if(deptIdList.size()>0){
            sqlFilter.append(tableAilas).append(dataFilter.deptId())
                    .append(" in(").append(StringUtils.join(deptIdList,","))
                    .append(")");
        }
        //没有本部门权限 也能查询本人数据
        if(dataFilter.user()){
            if(deptIdList.size()>0){
                sqlFilter.append(" or ");
            }
            sqlFilter.append(tableAilas).append(dataFilter.userId()).append("=").append(user.getId());
        }
        sqlFilter.append(")");
        return sqlFilter.toString();
    }
}
